<?php

namespace common\services;

use common\models\Tally;
use common\models\TallyVipOrder;
use function AlibabaCloud\Client\env;

class AppleServices extends BaseService
{
    private static $config = [
        'app_id' => '', //应用ID
        'secret' => '', //支付密钥
        //沙箱,现网
        'is_sandbox' => 0,
        'url_buy'     => "https://buy.itunes.apple.com/verifyReceipt", // 正式购买地址
        'url_sandbox' => "https://sandbox.itunes.apple.com/verifyReceipt",// 沙盒购买地址
        'pay_test' => 1,  //是否支付测试
        'is_screen_pay' => 0,
    ];



    public static function sendNotify($receiptDate = '',$transactionId = ''){

        $receiptDate = trim($receiptDate);
        if (!$receiptDate) {
            self::setError('购买凭证不存在');
        }
        if (strlen($receiptDate) < 20) {
            self::setError('购买凭证长度错误');
        }
        //购买地址
        $url = env('app_env') == 'dev'? self::$config['url_sandbox'] : self::$config['url_buy'];
        //去掉空格
        $receiptDate = str_replace(" ", "+", $receiptDate);
        $data = [
            "receipt-data" => $receiptDate
        ];
        $data = json_encode($data);

        $result = self::curl_post($url, $data);

        if (!$result) {
            self::setError('验证失败');
        }
        $result = json_decode($result, true);


        if ($result['status'] == '21007') {
            // 请求验证
            $url = self::$config['url_sandbox']; //沙盒购买地址
            $result = self::curl_post($url, $data);
            $result = json_decode($result, true);
        }
//        var_dump($result['receipt']['in_app']);exit;

        if ($result['status'] != 0) {
            self::setError("验证失败,订单购买凭证状态为" . $result['status']);exit;
        }

        $is_pay = false;
        //循环对比
        foreach ($result['receipt']['in_app'] as $value){
            if($value['transaction_id'] == $transactionId){
                $is_pay = true;
                break;
            }
        }
        //正常
        if($is_pay){
            $vip_order_info = TallyVipOrder::find()->where([
                'vip_order_code'=>$transactionId,
                'status'=>0
            ])->one();
            if(!$vip_order_info){
                self::setError("订单不存在");exit;
            }
            $vip_order_info->status = 1;
            $vip_order_info->save();
            $express = ($vip_order_info['vip_days']) * 86400;
            $tally_info = Tally::find()->where([
                'id'=>$vip_order_info['tally_id']
            ])->one();
            if($vip_order_info['vip_days'] > 10000){
                $express = strtotime('2099-12-31');
                $tally_info->express_time = $express;
                $tally_info->save();
            }else{
                $tally_info->updateCounters(['express_time'=>$express]);
            }
        }
    }


    public static function curl_post($url, $data, $headers = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


}